package dao

import (
	"context"
	"device-admin/internal/dal"
	"device-admin/internal/models"
	"os"

	"192.168.1.75/go-pkg/errorx"
)

type UpgradePackage struct{}

// Create 新增软件包
func (s UpgradePackage) Create(
	ctx context.Context,
	query *dal.Query,
	records []*models.UpgradePackage,
) ([]string, error) {
	uv := query.UpgradePackage
	err := uv.WithContext(ctx).Create(records...)
	ids := []string{}
	for _, record := range records {
		ids = append(ids, record.ID)
	}
	return ids, err
}

// Detail 升级包详情
func (s UpgradePackage) Detail(
	ctx context.Context,
	query *dal.Query,
	ID string,
) (*models.UpgradePackage, error) {
	uv := query.UpgradePackage
	return uv.WithContext(ctx).Where(uv.ID.Eq(ID)).Take()
}

// List 升级包列表
func (s UpgradePackage) List(
	ctx context.Context,
	query *dal.Query,
	version string,
	terminalType string,
	arch int,
	filePath string,
	fileMd5 string,
	page, limit int,
) (
	total int64,
	records []*models.UpgradePackage,
	err error,
) {
	up := query.UpgradePackage
	tx := up.WithContext(ctx).Where(up.TerminalType.Eq(terminalType))
	if arch >= 0 {
		tx = tx.Where(up.Arch.Eq(arch))
	}
	if version != "" {
		tx = tx.Where(up.Version.Eq(version))
	}
	if filePath != "" {
		tx = tx.Where(up.FilePath.Eq(filePath))
	}
	if fileMd5 != "" {
		tx = tx.Where(up.FileMD5.Eq(fileMd5))
	}
	// 获取总条数
	total, _ = tx.Count()

	// 获取记录
	records, err = tx.Order(up.CreatedAt.Desc()).
		Offset(GetPageOffset(page, limit)).
		Limit(GetPageLimit(limit)).
		Find()
	return total, records, err
}

// Delete 删除升级包
// 删除升级包记录及其对应的文件
func (s UpgradePackage) Delete(ctx context.Context, query *dal.Query, ID string) error {
	uv := query.UpgradePackage
	// 获取文件地址
	detail, err := s.Detail(ctx, query, ID)
	if err != nil {
		return err
	}
	// 删除软件包
	err = os.Remove(detail.FilePath)
	if err != nil {
		return errorx.New("软件包删除失败", -1)
	}
	// 先删除对应的文件
	res, _ := uv.WithContext(ctx).Where(uv.ID.Eq(ID)).Delete(&models.UpgradePackage{})
	if res.RowsAffected <= 0 {
		return errorx.New("软件包记录删除失败", -1)
	}
	return nil
}
